Disabling A Screensaver - Two Methods

Last Updated: 3rd May

METHOD ONE:

You could simply use that all-purpose Win32API function, SystemParametersInfo, to set the installed screensaver's active value to False. When your application is first opened, you would check to see if it was active, and if so, make it inactive:


SystemParametersInfo(SPI_GETSCREENSAVEACTIVE, 0, Addr(SaverActive), 0);
if SaverActive then
  SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, 0, nil, SPIF_UPDATEINIFILE);
Here, SaverActive is a global Boolean variable. Then when your application closes, you should re-enable the screensaver:

if SaverActive then
  SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, 1, nil, SPIF_UPDATEINIFILE);

METHOD TWO:

There's actually a much nicer way to disable a screensaver, which does not involve changing the Active setting of the currently installed screensaver. With this method you don't need to have a global variable, either. It goes like this. Every time the installed screensaver starts up it sends a WM_SYSCOMMAND message to the system, with the wParam parameter set to SC_SCREENSAVE. Well, why don't we just capture this message and swallow it up? Works like a charm, actually. I'll use the global TApplication object, and its event, OnMessage. Define a procedure in the interface section of your main form unit the following way:


procedure AppMessage(var Msg: TMsg; var Handled: Boolean);
Next, in the FormCreate method of your main form, add the following code:

Application.OnMessage := AppMessage;
Finally, in the impementation of the AppMessage we test for the WM_SYSCOMMAND message and the SC_SCREENSAVE wParam:

procedure TForm1.AppMessage(var Msg: TMsg; var Handled: Boolean);
begin
  if (Msg.Message = WM_SYSCOMMAND) and
    ((Msg.wParam) = SC_SCREENSAVE) then begin
    Handled := True;
  end;
end;
Setting Handled to True tells Windows that we have handled this message, and it does not require any further action.

lonewolf@tig.com.au